package cn.team11.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class ImageUtil {

    public static void uploadImg(final String dstUrl, String imgPath, final String dstFname, final Callback callback, Context ctx) throws IOException {
        Luban.with(ctx)
                .load(imgPath)                                   // 传人要压缩的图片列表
                .ignoreBy(100)                                  // 忽略不压缩图片的大小
//                .setTargetDir(getPath())                        // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        try {
                            FileInputStream fis = new FileInputStream(file);
                            byte[] imgBytes = new byte[fis.available()];
                            fis.read(imgBytes);
                            doUploadImg(dstUrl,dstFname, callback, imgBytes);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        T11Log.e(e);
                    }
                }).launch();    //启动压缩

    }

    private static void doUploadImg(String dstUrl,String dstFname, Callback callback, byte[] imgBytes) {
        RequestBody muiltipartBody = new MultipartBody.Builder()
                //一定要设置这句
                .setType(MultipartBody.FORM)
//                .addFormDataPart("password", "admin")//
                .addFormDataPart("dstFname", dstFname, RequestBody.create(MediaType.parse("application/octet-stream"), imgBytes))
                .build();
        final Request request = new Request.Builder()
                .post(muiltipartBody)
                .url(dstUrl)
                .build();
        OkHttpClient client = new OkHttpClient();

        Call call = client.newCall(request);
        call.enqueue(callback);
    }

    /**
     * Get bitmap from specified image path
     *
     * @param imgPath
     * @return
     */
    public static Bitmap getBitmap(String imgPath) {
        // Get bitmap through image path
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = false;
        newOpts.inPurgeable = true;
        newOpts.inInputShareable = true;
        // Do not compress
        newOpts.inSampleSize = 1;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeFile(imgPath, newOpts);
    }

    /**
     * Compress by quality,  and generate image to the path specified
     *
     * @param image
     * @param maxSize target will be compressed to be smaller than this size.(kb)
     * @throws IOException
     */
    public static byte[] compressAndGenImage(Bitmap image, int maxSize) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        // scale
        int options = 100;
        // Store the bitmap into output stream(no compress)
        image.compress(Bitmap.CompressFormat.PNG, options, os);
        // Compress by loop
        int flen = os.toByteArray().length/1024;
        if (flen> maxSize) {
            T11Log.d("compress Img");
            // Clean up os

            // interval 10
//            options -= 10;
            options = 100*maxSize/(flen);
            if (options<=0){
                options = 1;
            }

            T11Log.d("flen = "+flen);
            T11Log.d("maxSize = "+maxSize);
            T11Log.d("options = "+options);
            os.reset();
            image.compress(Bitmap.CompressFormat.PNG, options, os);
        }
        T11Log.d("compressed size = "+os.toByteArray().length/1024);
        return os.toByteArray();
    }

    public static byte[] compressImg(String imgPath, int maxSize) throws IOException {
        Bitmap img = getBitmap(imgPath);
        T11Log.d("get img success, imgPath = "+imgPath);
        return compressAndGenImage(img, maxSize);
    }

}